package top.infopub.mgr.fia.web;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.domain.TaxApplyDomain;
import top.infopub.mgr.fia.service.TaxApplyService;
import top.infopub.mgr.fia.vo.TaxApplyVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.fia.TaxApplyDetail;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;
import com.google.common.collect.Maps;


/**
 * 税费申请管理
 * @author wangw
 * @version 2020年1月14日
 * @see TaxApplyController
 * @since
 */
@Controller
@RequestMapping("/taxApply")
public class TaxApplyController extends GenericFlowController {

    @Autowired
    private TaxApplyService taxApplyService;
    
    @Autowired
    private OrgInfoService orgInfoService;
    
    @Autowired
    private StaffInfoService staffInfoService;
    
    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 税费申请列表
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        String bindOrgId = (String)SessionUserUtils.getSessionAttribute("bindOrgId");
        request.setAttribute("bindOrgId", bindOrgId);
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if(StringUtils.isEmpty(visibleOrgIds)){
            Map<String, Object> where = Maps.newHashMap();
            where.put("state", 1);
            where.put("orderCondition", " types asc, add_time asc");
            orgInfos = orgInfoService.selectByMapWhere(where);
        }else{
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "fia/lay-taxApply-list";
    }
    
    /**
     * 税费申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<TaxApplyDomain> queryDataByCondition(TaxApplyVo taxApplyVo, ParamPage paramPage) {
        Page<TaxApplyDomain> page = new Page<TaxApplyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (taxApplyVo.getEndDate() != null) {
            taxApplyVo.setEndDate(DateUtils.addDays(taxApplyVo.getEndDate(), 1));
        }
        page = taxApplyService.selectPageByDomainWhere(page, taxApplyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 税费申请-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<TaxApplyDomain> queryMyCheckDataByCondition(TaxApplyVo taxApplyVo, ParamPage paramPage) {
        Page<TaxApplyDomain> page = new Page<TaxApplyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (taxApplyVo.getEndDate() != null) {
            taxApplyVo.setEndDate(DateUtils.addDays(taxApplyVo.getEndDate(), 1));
        }
        taxApplyVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = taxApplyService.selectMyCheckByDomainWhere(page, taxApplyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }
    
    /**
     * 税费申请-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可税费申请的税费申请记录
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        String visibleOrgIds = (String)SessionUserUtils.getSessionAttribute("visibleOrgIds");
        List<OrgInfo> orgInfos = new ArrayList<OrgInfo>();
        if(StringUtils.isEmpty(visibleOrgIds)){
            OrgInfo orgInfo = new OrgInfo();
            orgInfo.setState(1);
            orgInfos = orgInfoService.selectByEntityWhere(orgInfo);
        }else{
            orgInfos = orgInfoService.selectByVisibleIds(visibleOrgIds);
        }
        request.setAttribute("orgInfos", orgInfos);
        return "fia/lay-taxApply-add";
    }
    
    /**
     * 根据id查询税费申请详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 税费申请Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request,String id, String processDealWith){
        Map<String, Object> map = new HashMap<String, Object>();
        TaxApplyVo taxApply = taxApplyService.selectById(id);
        map.put("taxApply", taxApply);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, taxApply.getProcessId());
        return new ModelAndView("fia/lay-taxApply-detail", map);
    }
    
    /**
     * 新增税费申请
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,TaxApplyVo taxApply) {
        String[] orderIdx = request.getParameterValues("orderIdx");//子项序号
        String[] taxTypes = request.getParameterValues("taxType");//子项-税费类型
        String[] taxAmounts = request.getParameterValues("taxAmount");//子项-税费金额
        
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        
        /**
         * 税费申请主表处理
         */
        String id = IdFactory.getUUIDUpper();
        taxApply.setId(id);
        taxApply.setHrStaffApplyId(vo.getHrStaffId());
        taxApply.setAddBy(vo.getId());
        taxApply.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("fia_tax_apply_codes");
        taxApply.setCodes(codes);
        // 处理processId
        taxApply.setProcessId(IdFactory.getUUIDUpper());
        taxApply.setProcessStatus("1");//审批中
        taxApply.setUptBy(vo.getId());
        taxApply.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        
        //子项处理
        List<TaxApplyDetail> taxApplyDetails = new ArrayList<TaxApplyDetail>();
        for(int i=0; i<orderIdx.length; i++){
            String orderId = orderIdx[i];
            TaxApplyDetail applyDetail = new TaxApplyDetail();
            String subId = IdFactory.getUUIDUpper();//自动生成主键
            applyDetail.setId(subId);
            applyDetail.setApplyId(id);
            applyDetail.setOrderIdx(Integer.parseInt(orderId));
            applyDetail.setTaxType(taxTypes[i]);
            applyDetail.setTaxAmount(new BigDecimal(taxAmounts[i]));
            applyDetail.setAddBy(vo.getId());
            applyDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
            taxApplyDetails.add(applyDetail);
        }

        taxApplyService.addTaxApply(taxApply, taxApplyDetails);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "税费申请 -新增税费申请：项目名="+taxApply.getProName(), null);
        return RspVo.getSuccessResponse();
    }
    
}
